//
//  ViewController.m
//  Net2
//
//  Created by Justsoso on 16/3/28.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "ViewController.h"
#import <TBXML.h>
#import "NetManager.h"
#import "def.h"

#import <SVProgressHUD.h>

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:kNotificantionLoginSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFail:) name:kNotificantionLoginFail object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    /* 移除通知 */
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (IBAction)loginBtnPressed:(id)sender
{
    [SVProgressHUD showWithStatus:@"正在登录"];
    NetManager *net = [NetManager shareNetManager];
    
    [net longWithUserName:self.usernameTextField.text andPassWord:self.passwordTextField.text];
}

- (void)loginSuccess
{
    
    [SVProgressHUD showWithStatus:@"登录成功"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
        [self performSegueWithIdentifier:@"gotoMain" sender:nil];
    });
}

- (void)loginFail:(NSNotification *)n
{
    [SVProgressHUD dismiss];
    NSError *error = n.userInfo[@"error"];
    NSString *message = [NSString stringWithFormat:@"错误信息:%@",[error localizedDescription]];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}




@end
